import os
import re
import time
import random
import tarfile
import filetype


def dir_init(file_path_all):
    file_path_all = os.path.dirname(file_path_all)
    if not os.path.exists(file_path_all):
        print("初始化文件夹：", file_path_all)
        os.makedirs(file_path_all)


def get_time_info(file_path):
    time_info = {
        "time_view": time.ctime(os.path.getatime(file_path)),
        "time_create": time.ctime(os.path.getctime(file_path)),
        "time_change": time.ctime(os.path.getmtime(file_path))
    }
    return time_info


def allow_origin(self):
    allow_list = [
        'http://127.0.0.1:7100',
    ]
    if 'Origin' in self.request.headers:
        Origin = self.request.headers['Origin']
        # 域名
        re_ret = re.match(r".{1,}\.(xixi.com|haha.com)", Origin)
        # 内网和本地
        re_ret2 = re.match(r"^(192.168.1.*|127.0.0.1.*|192.168.2.*)", Origin)
        if True or re_ret or re_ret2 or Origin in allow_list:
            self.set_header("Access-Control-Allow-Origin", Origin)  # 这个地方可以写域名也可以是*
            self.set_header("Access-Control-Allow-Headers", "x-requested-with")
            self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')


def file_del(_file_path):
    if os.path.exists(_file_path):
        os.rename(_file_path, os.path.join(os.path.dirname(_file_path),
                                           "bak_" + time.strftime("%Y%m%d%H%M%S_") + os.path.basename(_file_path)))


def file_size_human_print(size):
    if size < 1024:
        return str(size) + "Bytes"
    elif size < 1024 * 1024:
        return str(size // 1024) + "KB"
    elif size < 1024 * 1024 * 1024:
        return str(size // 1024 // 1024) + "MB"
    elif size < 1024 * 1024 * 1024 * 1024:
        return str(size // 1024 // 1024 // 1024) + "GB"


def get_random_str(length=4):
    str_random = "".join([str(random.randint(0, 9)) for _ in range(length)])
    return str_random


def get_time_stamp():
    return time.strftime("%Y%m%d%H%M%S")


def get_file_name_random():
    return get_time_stamp() + get_random_str()


def get_time_stamp_random(length_random=4):
    return get_time_stamp() + get_random_str(length_random)


def init_session_path(session_token=""):
    if session_token == "":
        session_token = get_file_name_random()
        return session_token
    path_session = "static/session"
    path_session_one = os.path.join(path_session, session_token)
    dir_init(os.path.join(path_session_one, "temp"))
    return path_session_one


def child_dict2list(child):
    print(child)
    child_list = []
    if len(child) == 0:
        return child_list
    for child_one in child.values():
        child_one["dir_child"] = child_dict2list(child_one["dir_child"])
        if len(child_one["dir_child"]) == 0:
            child_one.pop("dir_child")
        child_list.append(child_one)
    return child_list


def get_file_tree_by_base_path_bak(base_path):
    dir_tree = {}
    for r, d, f in sorted(os.walk(base_path)):
        dir_path = r
        r = r.lstrip(base_path)
        if len(f) == 0:
            dir_tree = {
                "dir_id": os.path.basename(dir_path),
                "dir_path": dir_path,
                "dir_child": {}
            }
            continue
        dir_tree_cur = dir_tree
        for r_part in r.split(os.sep)[:]:
            if "dir_child" not in dir_tree_cur:
                dir_tree_cur["dir_child"] = {}
            if r_part in dir_tree_cur["dir_child"]:
                dir_tree_cur = dir_tree_cur["dir_child"][r_part]
            else:
                dir_tree_cur["dir_child"][r_part] = {"dir_id": os.path.basename(dir_path), "dir_path": dir_path,
                                                     "dir_child": {}, "other_data": ""}
                dir_tree_cur["dir_child"][r_part]["dir_name"] = os.path.basename(dir_path)
                dir_tree_cur["dir_child"][r_part]["dir_info"] = "一些提示信息"
    return child_dict2list(dir_tree["dir_child"])


def get_file_type(file_path):
    kind = filetype.guess(file_path)
    if kind is None:
        print('Cannot guess file type!')
        return

    print('File extension: %s' % kind.extension)
    print('File MIME type: %s' % kind.mime)


def get_file_tree_by_base_path(path_base, path_curr=""):
    if path_curr == "":
        path_curr = os.path.abspath(path_base)
    node_label = os.path.basename(path_curr)
    node_path = os.path.normpath(path_curr).replace(os.path.normpath(os.path.abspath(path_base)), "")
    if not os.path.isdir(path_curr):
        return [{
            "label": node_label,
            "path": node_path,
            "isdir": os.path.isdir(path_curr),
            "type": "file",
            "editable": True
        }]
    child_path_list = os.listdir(path_curr)
    if len(child_path_list) == 0:
        return []
    node_child = []
    for child_path in child_path_list:
        node_child += get_file_tree_by_base_path(path_base, os.path.join(path_curr, child_path))
    node_cur = {
        "label": node_label,
        "path": node_path,
        "isdir": os.path.isdir(path_curr),
        "type": "dir",
        "children": node_child
    }
    return [node_cur]


def uncompress_tar_bz2(path_tar, path_save):
    archive = tarfile.open(path_tar, 'r:bz2')
    archive.debug = 1  # Display the files beeing decompressed.
    for tarinfo in archive:
        archive.extract(tarinfo, path_save)
    archive.close()


def uncompress_tar_gz(path_tar, path_save):
    archive = tarfile.open(path_tar, 'r:gz')
    archive.debug = 1
    for tarinfo in archive:
        archive.extract(tarinfo, path_save)
    archive.close()


def compress_tar_gz(path_tar, path_save):
    with tarfile.open(path_save, "w:gz") as tar:
        tar.add(path_tar, arcname=os.path.basename(path_tar))


#
# # 逐个添加文件打包，未打包空子目录。可过滤文件。
# # 如果只打包不压缩，将"w:gz"参数改为"w:"或"w"即可。
# def make_targz_one_by_one(output_filename, source_dir):
#     tar = tarfile.open(output_filename, "w:gz")
#     for root, dir, files in os.walk(source_dir):
#         for file in files:
#             pathfile = os.path.join(root, file)
#             tar.add(pathfile)
#     tar.close()
#
#
# make_targz('test.tar.gz', "E:\python_sample\libs")
# make_targz_one_by_one('test01.tgz', "E:\python_sample\libs")

if __name__ == '__main__':
    # print(get_random_str())
    # # print(get_file_tree_by_base_path("../"))
    # print(get_file_type("./database_init.sql"))
    compress_tar_gz("../static/session/202210071912078157/source_gitee/openEuler-20.03-LTS-SP1/rpm",
                    "../static/file_save/rpmbuild.tar.gz")
